package bg.code.commons.plugin;

import bg.code.commons.builder.idea.ProjectPluginConfig;
import bg.code.commons.builder.project.ToolConfigurationData;
import bg.code.commons.builder.utils.JavaFieldUtil;
import bg.code.commons.builder.utils.JavaTableUtil;
import bg.code.commons.builder.utils.Strings;
import bg.code.commons.builder.vo.ColumnDescriptor;
import bg.code.commons.plugin.ui.ConfigDialog;
import bg.code.commons.plugin.ui.ErrorDialog;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.PsiJavaFileImpl;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilBase;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 郑兴泉 956607644@qq.com
 * @data 2020/3/16
 * 描述：
 */
public class GeneratorAction extends DumbAwareAction {


    private Project project = null;
    private Editor editor = null;
    private ToolConfigurationData configuration = ToolConfigurationData.getInstance();

    @Override
    public void actionPerformed(AnActionEvent e) {
        this.project = e.getData(CommonDataKeys.PROJECT);
        this.editor = e.getData(CommonDataKeys.EDITOR);
        PsiClass rootClass = getTargetClass(e, editor);
        if (null == rootClass) {
            new ErrorDialog(this.project).show();
            return;
        }
        try {
            // 方法执行
            doActionPerformed(rootClass);
        } catch (Exception ex) {
            ErrorDialog.createError(this.project, "package错误");
            return;
        }
    }


    /**
     * 具体执行方法
     */
    public void doActionPerformed(PsiClass rootClass) {
        PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
        if (psiFile instanceof PsiJavaFileImpl) {
            PsiJavaFileImpl psiJavaFile = (PsiJavaFileImpl) psiFile;

            Document document = editor.getDocument();
            List<ColumnDescriptor> javaFields = new ArrayList();
            // 得到所有字段
            PsiField[] psiFields = psiJavaFile.getClasses()[0].getFields();
            if (psiFields != null) {
                for (PsiField field : psiFields) {
                    String fieldName = JavaFieldUtil.getFieldNameAndIsColumn(field);
                    if (Strings.isNotBlank(fieldName)) {
                        // 组装字段属性
                        ColumnDescriptor javaField = JavaFieldUtil.getNutzFw(field);
                        javaField.setColumnName(fieldName);
                        javaFields.add(javaField);
                    }
                }
            }
            if (!javaFields.isEmpty()) {
                ConfigDialog fieldDialog = null;
                try {
                    ProjectPluginConfig config = new ProjectPluginConfig(ApplicationManager.getApplication(), CommandProcessor.getInstance(), document, project, editor, psiFile, javaFields);
                    config.setConfiguration(this.configuration);
                    config.setmClass(rootClass);
                    config.setTableDescriptor(JavaTableUtil.getTableData(rootClass, javaFields));
                    fieldDialog = new ConfigDialog(config);
                } catch (Exception ex) {
                    ErrorDialog.createError(this.project, ex.getMessage());
                    return;
                }
                fieldDialog.pack();
                fieldDialog.show();
                if (!fieldDialog.isOK()) {
                    return;
                }
            } else {
                ErrorDialog.createError(this.project, "没有指定的注解！");
            }
        } else {
            ErrorDialog.createError(this.project, "不是java类！");
        }
    }

    @Override
    public void update(AnActionEvent event) {
        Project project = event.getProject();
        Editor editor = CommonDataKeys.EDITOR.getData(event.getDataContext());
        PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
        if ((psiFile instanceof PsiJavaFileImpl)) {
            setEnabledInModalContext(true);
            getTemplatePresentation().setEnabledAndVisible(true);
        } else {
            setEnabledInModalContext(false);
            getTemplatePresentation().setEnabledAndVisible(false);
        }
    }

    /**
     * 得到要生成代码的类
     */
    private PsiClass getTargetClass(AnActionEvent e, Editor editor) {
        PsiFile file = e.getData(LangDataKeys.PSI_FILE);
        int offset = editor.getCaretModel().getOffset();
        PsiElement element = file.findElementAt(offset);
        return  PsiTreeUtil.getParentOfType(element, PsiClass.class);
    }
}
